package com.petecat.interchan.base.warning.config.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mhuang.common.util.DataUtils;
import com.petecat.interchan.base.project.entity.EsEwarningHardwareConfig;
import com.petecat.interchan.base.project.service.IProjectService;
import com.petecat.interchan.base.warning.config.entity.BsWarningConfig;
import com.petecat.interchan.base.warning.config.entity.EsEwarningHardWare;
import com.petecat.interchan.base.warning.config.entity.EsRemarkVO;
import com.petecat.interchan.base.warning.config.entity.EsWarningNoticeVO;
import com.petecat.interchan.base.warning.config.entity.WarningEmpl;
import com.petecat.interchan.base.warning.config.mapper.IWarningConfigMapper;
import com.petecat.interchan.base.warning.config.service.IWarningConfigService;
import com.petecat.interchan.base.warning.empl.entity.BsWarningEmpl;
import com.petecat.interchan.base.warning.empl.service.IWarningEmplService;
import com.petecat.interchan.base.warning.rule.entity.BsWarningRule;
import com.petecat.interchan.base.warning.rule.service.IWarningRuleService;
import com.petecat.interchan.base.warning.rule.service.impl.WarningRuleServiceImpl;
import com.petecat.interchan.core.exception.BusinessException;
import com.petecat.interchan.core.service.impl.BaseServiceImpl;
import com.petecat.interchan.es.EsDaoInter;
import com.petecat.interchan.protocol.Result;
import com.petecat.interchan.protocol.base.config.dto.BsWarningConfigAddDTO;
import com.petecat.interchan.protocol.base.config.dto.BsWarningConfigQryDTO;
import com.petecat.interchan.protocol.base.config.dto.BsWarningConfigUpdDTO;
import com.petecat.interchan.protocol.base.config.dto.DelEmplDTO;
import com.petecat.interchan.protocol.base.config.vo.BsWarningConfigQryVO;
import com.petecat.interchan.protocol.base.config.vo.BsWarningConfigTreeVO;
import com.petecat.interchan.protocol.base.config.vo.BsWarningConfigUpdVO;
import com.petecat.interchan.protocol.base.empl.dto.BsWarningEmplQryDTO;
import com.petecat.interchan.protocol.base.rule.dto.BsWarningRuleAddDTO;
import com.petecat.interchan.protocol.base.rule.dto.BsWarningRuleUpdDTO;
import com.petecat.interchan.protocol.data.Page;
import com.petecat.interchan.protocol.data.PageVO;
import com.petecat.interchan.protocol.sso.company.vo.SysCompanyQryVO;
import com.petecat.interchan.protocol.sso.companyempl.vo.BsSmsQryVO;
import com.petecat.interchan.protocol.sso.sysuser.SysUserAddDTO;
import com.petecat.interchan.redis.IdWorker;
import com.petecat.interchan.redis.commands.IRedisExtCommands;

@Service
public class WarningConfigServiceImpl extends BaseServiceImpl<BsWarningConfig, String> implements IWarningConfigService {
	
	@Autowired
	private IWarningConfigMapper configMapper;
	
	@Autowired
	private IRedisExtCommands redisExtCommands;
	
	@Autowired
	private Environment environment;
	
	@Autowired
	private IWarningRuleService warningRuleService;
	
	@Autowired
	private IWarningEmplService warningEmplService;
	
	@Autowired
	private IProjectService projectService;
	
	@Autowired
	private EsDaoInter esDao;
	
	private final static Integer ZERO=0;
	
	private final static String SYS_COMPANY_USER_PREKEY="sys_company_user";
	
	private final static String SYUSER_REDIS_USERID_TO_USER_PREKEY="syur_user_uid_";
	
	private final static String userNotExites = "user_not_exites";

	private final static String BS_EWARNING="bs_ewarning";

	private final static Logger logger = LoggerFactory.getLogger(WarningRuleServiceImpl.class);
	@Override
	public PageVO<BsWarningConfigQryVO> queryWarningConfigByPage(BsWarningConfigQryDTO bsWarningConfigQryDTO) {
		SysUserAddDTO sysUserAddDTO = redisExtCommands.hget(SYUSER_REDIS_USERID_TO_USER_PREKEY, bsWarningConfigQryDTO.getUserId(), SysUserAddDTO.class);
		if(null == sysUserAddDTO) {
			throw new BusinessException(Result.SYS_RESULT_FAILD,
					environment.getProperty(userNotExites));
		}
		String user = "0".equals(sysUserAddDTO.getIsMaster()) ? sysUserAddDTO.getUserid():null;
		bsWarningConfigQryDTO.setUserId(user);
		BsWarningConfig bsWarningConfig = DataUtils.copyTo(bsWarningConfigQryDTO, BsWarningConfig.class);
		int count = this.configMapper.count(bsWarningConfig);
		PageVO<BsWarningConfigQryVO> pageVo = new PageVO<>();
		if(count > 0) {
			Page<BsWarningConfig> page = new Page<>();
			page.setRows(bsWarningConfigQryDTO.getRows());
			page.setStart(bsWarningConfigQryDTO.getStart());
			page.setRecord(bsWarningConfig);
			List<BsWarningConfig> companyList = this.configMapper.page(page);
			pageVo.setResult(DataUtils.copyTo(companyList, BsWarningConfigQryVO.class));
		}
		pageVo.setTotalSize(count);
		return pageVo;
	}
	
	/**
	 * 新增预警配置基本信息
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveWarningConfig(BsWarningConfigAddDTO bsWarningConfigAddDTO, String userId) {
		BsWarningConfig config = DataUtils.copyTo(bsWarningConfigAddDTO, BsWarningConfig.class);
		String projectId = bsWarningConfigAddDTO.getProjectId();
		config.setCreateTime(new Date());
		config.setOperatorTime(new Date());
		config.setId(String.valueOf(new IdWorker().nextId()));
		config.setOperaorUserId(userId);
		config.setUserId(userId);
		this.configMapper.save(config);
		//如果启用当前规则就警用其他规则
		if("1".equals(config.getStatus())) {
			//通过项目ID将所有的配置关闭,指定的配置状态修改为启用
			configMapper.updateStatesByProjectId(projectId,config.getId());
		}
		//添加业务规则	
		List<BsWarningRuleAddDTO> warningRuleList = bsWarningConfigAddDTO.getWarningRuleList();
		for (BsWarningRuleAddDTO bsWarningRuleAddDTO : warningRuleList) {
			bsWarningRuleAddDTO.setEwaringId(config.getId());
		}
		//通过项目ID查询项目Token
		String token = projectService.getProjectTokenById(projectId);
		warningRuleService.saveWarningRule(warningRuleList,userId,token,config.getStatus());
	}
	
	/**
	 * 查询预警配置Tree
	 */
	@Override
	public PageVO<BsWarningConfigTreeVO> queryWarningConfigTree(BsWarningConfigQryDTO bsWarningConfigQryDTO) {
		SysUserAddDTO sysUserAddDTO = redisExtCommands.hget(SYUSER_REDIS_USERID_TO_USER_PREKEY, bsWarningConfigQryDTO.getUserId(), SysUserAddDTO.class);
		if(null == sysUserAddDTO) {
			throw new BusinessException(Result.SYS_RESULT_FAILD,
					environment.getProperty(userNotExites));
		}
		String user = "0".equals(sysUserAddDTO.getIsMaster()) ? sysUserAddDTO.getUserid():null;
		bsWarningConfigQryDTO.setUserId(user);
		List<BsWarningConfigTreeVO> treeVO = this.configMapper.queryWarningConfigTree(bsWarningConfigQryDTO);
		PageVO<BsWarningConfigTreeVO>  page = new PageVO<BsWarningConfigTreeVO>();
		if(!treeVO.isEmpty()) {
			page.setResult(treeVO);
		}
		return page;
	}
	
	/**
	 * 查询预警配置模块
	 */
	@Override
	public BsWarningConfigUpdVO queryWarningConfig(String configId,String userId) {
		//最终返回
		BsWarningConfigUpdVO vo = new BsWarningConfigUpdVO();
		//获取配置信息
		BsWarningConfig configPo = getConfigByID(configId);
		if(null != configId) {
			vo.setProjectId(configPo.getProjectId());
			vo.setName(configPo.getName());
		}
		List<BsWarningEmpl> emplList = null;
		List<BsWarningEmplQryDTO> qryDto  = null;
		//获取规则List
		List<BsWarningRule> ruleList = warningRuleService.queryWarningListById(configId);
		if(!ruleList.isEmpty()){
			List<BsWarningRuleAddDTO> ruleaddList = DataUtils.copyTo(ruleList, BsWarningRuleAddDTO.class);
			if(!ruleaddList.isEmpty()) {
				//循环通过规则ID获取预警人员
				for (BsWarningRuleAddDTO dto : ruleaddList) {
					emplList = warningEmplService.queryEmplListByRuleId(dto.getId());
					if(null != emplList) {
						qryDto = DataUtils.copyTo(emplList, BsWarningEmplQryDTO.class);
						for (BsWarningEmplQryDTO d : qryDto) {
							d.setUserName(redisExtCommands.hget(ZERO,SYS_COMPANY_USER_PREKEY, d.getUserId(), SysCompanyQryVO.class).getName());
						}
						dto.setWarningEmplList(qryDto);
					}
				}
			}
			vo.setWarningRuleList(ruleaddList);
		}
		return vo;
	}
	
	
	
	/**
	 * 通过ID获取配置信息
	 * @return
	 */
	public BsWarningConfig getConfigByID(String config) {
		BsWarningConfig configPo = this.configMapper.getById(config);
		if(null != configPo) {
			return configPo;
		}
		return null;
	}
	
	/**
	 * 修改预警配置信息
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateWarningConfig(BsWarningConfigUpdDTO bsWarningConfigUpdDTO, String userId) {
		//修改配置基本信息
		BsWarningConfig bsWarningConfig = DataUtils.copyTo(bsWarningConfigUpdDTO, BsWarningConfig.class);
		//如果启用当前规则就警用其他规则
		if("1".equals(bsWarningConfig.getStatus())) {
			//通过项目ID将所有的配置关闭,指定的配置状态修改为启用
			configMapper.updateStatesByProjectId(bsWarningConfigUpdDTO.getProjectId(),bsWarningConfigUpdDTO.getId());
		}
		bsWarningConfig.setOperaorUserId(userId);
		bsWarningConfig.setOperatorTime(new Date());
		this.configMapper.update(bsWarningConfig);
		//获取项目ID查询项目Token
		String projectId = bsWarningConfigUpdDTO.getProjectId();
		String token = projectService.getProjectTokenById(projectId);
		//修改规则信息
		List<BsWarningRuleUpdDTO> warningRuleList = bsWarningConfigUpdDTO.getWarningRuleList();
		//删除规则时，将对应的人员删除 
		//传入一个删除规则ID数组，如果前台传来的又数据ID就修改 没有的直接删除数字ID
		String[] delRules = bsWarningConfigUpdDTO.getDelRules();
		if(null != delRules && delRules.length > 0) {
			//删除规则
			warningRuleService.deleteRuleById(delRules);
			//删除规则对应的表中残余多余预警人员
			warningEmplService.delEmplsByRuleIds(delRules);
		}
		//先通过RuleId和UserId删除多个预警人员 
		List<DelEmplDTO> delEmplDTO = bsWarningConfigUpdDTO.getDelEmplDTO();
		if(!delEmplDTO.isEmpty()) {
			warningEmplService.delEmplsByUserIdAndRuleId(delEmplDTO);
		}
		List<BsWarningRule> ruleList = new ArrayList<BsWarningRule>();
		BsWarningRule rule = null;
		List<BsWarningEmplQryDTO> warningEmplList = null;
		for (BsWarningRuleUpdDTO upd : warningRuleList) {
			rule = DataUtils.copyTo(upd, BsWarningRule.class);
			if(null != rule.getId() && !rule.getId().equals("")) {
				rule.setOperatorTime(new Date());
				rule.setOperaorUserId(userId);
				warningRuleService.update(rule);
			}else {
				rule.setCreateTime(new Date());
				rule.setOperaorUserId(userId);
				rule.setUserId(userId);
				rule.setOperatorTime(new Date());
				rule.setStatus("1");
				rule.setId(String.valueOf(new IdWorker().nextId()));
				rule.setEwaringId(bsWarningConfigUpdDTO.getId());
				warningRuleService.save(rule);
			}
			warningEmplList = upd.getWarningEmplList();
			if(!warningEmplList.isEmpty()) {
				//删除所有预警人员
				warningEmplService.delEmplsByRuleId(rule.getId());
				for (BsWarningEmplQryDTO empl : warningEmplList) {
					empl.setRuleId(rule.getId());
					//删除所有相关预警人员后 再循环添加
					warningEmplService.save(DataUtils.copyTo(empl, BsWarningEmpl.class));
				}
				// 通过userId去获取预警人员信息 缓存里
				warningEmplList.parallelStream().forEach(e -> {
					String hget = redisExtCommands.hget(ZERO, "sys_company_user", e.getUserId());
					JSONObject json = JSONObject.parseObject(hget);
					e.setUserName(json.getString("name"));
					e.setSms(json.getString("sms"));
					e.setEmail(json.getString("email"));
				});
				// 存规则
				try {
					redisExtCommands.hset(ZERO, "sys_company_" + token + "_user", upd.getId(), warningEmplList);
				} catch (Exception e) {
					logger.error("saveWarningRule 将预警规则存进Redis失败,预警规则配置为：{}", warningEmplList, e);
				}
				
			}
			//添加到集合中 添加缓存
			ruleList.add(rule);
		}
		//存入预警信息  key:token  value:规则列表 :config
		if("1".equals(bsWarningConfigUpdDTO.getStatus())) {
			try{
				redisExtCommands.hset(ZERO, BS_EWARNING, token, ruleList);
			} catch (Exception e) {
				logger.error("saveWarningRule 将预警配置存进Redis失败,预警配置为：{}",ruleList,e);
			}
		}
		
	}
	
	/**
	 * 通过预警配置Id删除预警配置信息
	 */
	@Override
	public void removeWarningConfigByConfigId(String configId) {
		//通过配置ID删除配置
		configMapper.removeWarningConfigByConfigId(configId);
		//通过配置ID查询规则id 开始数组
		List<BsWarningRule> warningList = warningRuleService.queryWarningListById(configId);
		if(!warningList.isEmpty()) {
			String[] delRules = new String[warningList.size()];
			//获取到删除规则的ID然后删除规则和预警人员
			for (int i=0;i<warningList.size();i++) {
				delRules[i] = warningList.get(i).getId();
			}
			//删除规则
			warningRuleService.deleteRuleById(delRules);
			//删除规则对应的表中残余多余预警人员
			warningEmplService.delEmplsByRuleIds(delRules);
		}
		
	}
	
	/**
	 * 通过预警配置Id修改预警配置状态信息
	 */
	@Override
	public void updateStatusConfigById(String configId, String projectId) {
		//通过项目ID将所有的配置关闭,指定的配置状态修改为启用
		configMapper.updateStatesByProjectId(projectId,configId);
		//获取规则List
		List<BsWarningRule> ruleList = warningRuleService.queryWarningListById(configId);
		if(!ruleList.isEmpty()) {
			//存入预警信息  key:token  value:规则列表 :config
			String token = projectService.getProjectTokenById(projectId);
			try{
				redisExtCommands.hset(ZERO, BS_EWARNING, token, ruleList);
			} catch (Exception e) {
				logger.error("saveWarningRule 将预警配置存进Redis失败,预警配置为：{}",ruleList,e);
			}
		}
	}
	
	/**
	 * 通过规则ID查询到配置信息后，通过配置ID查询配置信息
	 */
	@Override
	public BsWarningConfig getEwarningConfigIdByRuleId(String ruleId) {
		return configMapper.getEwarningConfigIdByRuleId(ruleId);
	}
	
	/**
	 * 查询ES预警消息通知
	 */
	@Override
	public List<EsWarningNoticeVO> queryEsWarningNotice(String userId) {
		TransportClient client = null;
		 String sourceAsString = null;
		 String ruleId = null;
		 BsWarningConfig warningConfig = null;
		 String configName = null;
		 String remark = null;
		 EsWarningNoticeVO warningNoticeVO = null;
		 EsRemarkVO esRemarkVO = null;
		 List<EsWarningNoticeVO> noticeList = new ArrayList<>();
		 //
		 List<EsRemarkVO> remarkVoList = new ArrayList<>();
		 //判断是否存在过
		 List<String> remarkList = new ArrayList<>();
		 List<String> configIdList = new ArrayList<>();
		//存多个RuleId
		 List<String> ruleIdList = new ArrayList<>();
		//存多个备注
		 List<String> remarkAll = new ArrayList<>();
		//存多个备注次数
		 List<Integer> remarkCountAll = new ArrayList<>();
		 JSONObject warningObject = null;
		 try {
			client = esDao.getClient();
			//预警状态
			TermQueryBuilder ewarningStatus = QueryBuilders.termQuery("ewarningStatus", "1");
			//未读条件
			TermQueryBuilder readStatus = QueryBuilders.termQuery("readStatus", "0");
			
			BoolQueryBuilder mustContent = QueryBuilders.boolQuery().must(ewarningStatus).must(readStatus);
			
			SearchResponse actionGet = client.prepareSearch("monitor-ewarning-hardware")
															 .setSize(1000)
														  	 .setQuery(mustContent)
															 .execute().actionGet();
			SearchHits hits = actionGet.getHits();
			//修改备注VO中的CountList
			int y = 0;
			//计数
			int count = 0;
			if(hits.getHits().length > 0) {
				for (SearchHit hit : hits.getHits()) {
					sourceAsString = hit.getSourceAsString();
					warningObject = JSONObject.parseObject(sourceAsString);
					ruleId = warningObject.getString("id");
					warningConfig = this.getEwarningConfigIdByRuleId(ruleId);
					if(configIdList.contains(warningConfig.getId())) {
						//设置配置数量+1
						warningNoticeVO.setConfigCount(warningNoticeVO.getConfigCount()+1);
						remark = warningObject.getString("remark");
						if(remarkAll.contains(remark)){
							//索引归0
							y = 0;
							for (String str : remarkAll) {
								if(remark.equals(str)){
									break;
								}
								y++;
							}
							count = remarkCountAll.get(y).intValue();
							remarkCountAll.set(y, count+1);
						}else {
							remarkCountAll.add(1);
							remarkAll.add(remark);
							//添加RuleId
							ruleIdList.add(ruleId);
						}
					}else {
						warningNoticeVO = new EsWarningNoticeVO();
						configIdList.add(warningConfig.getId());
						configName = warningConfig.getName();
						warningNoticeVO.setConfigCount(1);
						warningNoticeVO.setConfigName(configName);
						esRemarkVO = new EsRemarkVO();
						remark = warningObject.getString("remark");
						remarkAll.add(remark);
						remarkCountAll.add(1);
						//设置备注
						esRemarkVO.setRemarkList(remarkAll);
						//设置次数
						esRemarkVO.setRemarkCountList(remarkCountAll);
						//添加RuleId
						ruleIdList.add(ruleId);
						esRemarkVO.setRuleIdList(ruleIdList);
						//存到List判断是否存在了
						remarkList.add(remark);
						remarkVoList.add(esRemarkVO);
						warningNoticeVO.setRemarkVOList(remarkVoList);
						noticeList.add(warningNoticeVO);
					}
				}
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(client != null ) {
				esDao.resume(client);
			}
		}
		return noticeList;
	}

	@Override
	public List<EsEwarningHardWare> getWarningByRuleId(String ruleId, String userId) {
		TransportClient client = null;
		String sourceAsString = "";
		List<EsEwarningHardWare> wareList = new ArrayList<>();
		EsEwarningHardWare ewarningHardWare = null;
		JSONObject parseObject = null;
		List<WarningEmpl> emplList = null;
		WarningEmpl empl = null;
		try {
			client = esDao.getClient();
			//设置规则ID为条件
			TermQueryBuilder ruleIdQuery = QueryBuilders.termQuery("id", ruleId);
			//预警状态
			TermQueryBuilder ewarningStatus = QueryBuilders.termQuery("ewarningStatus", "1");
			//未读条件
			TermQueryBuilder readStatus = QueryBuilders.termQuery("readStatus", "0");
			BoolQueryBuilder mustContent = QueryBuilders.boolQuery().must(ruleIdQuery).must(ewarningStatus).must(readStatus);
			SearchResponse actionGet = client.prepareSearch("monitor-ewarning-hardware").setSize(1000)
														  	 .setQuery(mustContent)
														  	 .addSort("sendTime", SortOrder.ASC)
															 .execute().actionGet();
			SearchHits hits = actionGet.getHits();
			if(hits.getHits().length > 0) {
				for (SearchHit hit : hits.getHits()) {
					emplList = new ArrayList<>();
					ewarningHardWare = new EsEwarningHardWare();
					sourceAsString = hit.getSourceAsString();
					parseObject = JSONObject.parseObject(sourceAsString);
					ewarningHardWare.setId(hit.getId());
					ewarningHardWare.setReadStatus(parseObject.getString("readStatus"));
					ewarningHardWare.setRemark(parseObject.getString("remark"));
					ewarningHardWare.setStopTime(stampToDate(parseObject.getString("stopTime")));
					ewarningHardWare.setRuleId(parseObject.getString("id"));
					ewarningHardWare.setEwarningStatus(parseObject.getString("ewarningStatus"));
					ewarningHardWare.setTitle(parseObject.getString("title"));
					ewarningHardWare.setSendTime(stampToDate(parseObject.getString("sendTime")));
					//获取用户List信息
					JSONArray jsonArray = parseObject.getJSONArray("user");
					Iterator<Object> iterator = jsonArray.iterator();
					while (iterator.hasNext()) {
						JSONObject next =  (JSONObject)iterator.next();
						empl = new WarningEmpl();
						empl.setEmail(next.getString("email"));
						empl.setIsEmail(next.getString("isEmail"));
						empl.setIsSms(next.getString("isSms"));
						empl.setRuleId(next.getString("ruleId"));
						empl.setSms(next.getString("sms"));
						empl.setUserId(next.getString("userId"));
						empl.setUserName(next.getString("userName"));
						emplList.add(empl);
					}
					ewarningHardWare.setEmplList(emplList);
					wareList.add(ewarningHardWare);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(client != null) {
				esDao.resume(client);
			}
		}
		return wareList;
	}
	
	
	/**
	 * 将时间戳转换为时间
	 * @param time
	 * @param format
	 * @return
	 */
	public String stampToDate(String time) {
		String res = "";
		if(time != null) {
			time = time + "000";
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			long lt = new Long(time);
			Date date = new Date(lt);
			res = simpleDateFormat.format(date);
		}
		return res;
	}
	
	/**
	 * 根据ID修改指定的 是否已读状态
	 */
	@Override
	public void updateEsWarningReadStatusById(List<String> ids, String ruleId,String userId) {
		TransportClient client = null;
			try {
				client = esDao.getClient();
				UpdateRequest uRequest = new UpdateRequest();
				uRequest.index("monitor-ewarning-hardware");
				uRequest.type("monitor-ewarning-hardware");
				uRequest.doc(XContentFactory.jsonBuilder()
											.startObject()
											.field("readStatus", "1")
											.endObject());
				//rule等于null 代表选择了具体，不等于空相当于要修改全部当前规则下的只读状态
				if(ruleId == null && ids.size() > 0) {
					for (String id : ids) {
						uRequest.id(id);
						client.update(uRequest);
					}
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				if(client != null) {
					esDao.resume(client);
				}
			}
	}
	
	/**
	 * 通过EsID查询对应的多个预警人员
	 */
	@Override
	public PageVO<WarningEmpl> getWarningEmplByEsId(String esId, String userId) {
		String sourceAsString = "";
		JSONObject parseObject = null;
		List<WarningEmpl> emplList = null;
		WarningEmpl empl = null;
		PageVO<WarningEmpl> emplPage = new PageVO<>();
		TransportClient client = null;
		try {
			client = esDao.getClient();
			TermQueryBuilder termQuery = QueryBuilders.termQuery("_id", esId);
			SearchResponse actionGet = client.prepareSearch("monitor-ewarning-hardware")
									.setQuery(termQuery)
									.execute()
									.actionGet();
			SearchHits hits = actionGet.getHits();
			if(hits.getHits().length > 0) {
				emplList = new ArrayList<>();
				for (SearchHit hit : hits.getHits()) {
					sourceAsString = hit.getSourceAsString();
					parseObject = JSONObject.parseObject(sourceAsString);
					//获取用户List信息
					JSONArray jsonArray = parseObject.getJSONArray("user");
					Iterator<Object> iterator = jsonArray.iterator();
					while (iterator.hasNext()) {
						JSONObject next =  (JSONObject)iterator.next();
						empl = new WarningEmpl();
						empl.setEmail(next.getString("email"));
						empl.setIsEmail(next.getString("isEmail"));
						empl.setIsSms(next.getString("isSms"));
						empl.setRuleId(next.getString("ruleId"));
						empl.setSms(next.getString("sms"));
						empl.setUserId(next.getString("userId"));
						empl.setUserName(next.getString("userName"));
						emplList.add(empl);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(client != null) {
				esDao.resume(client);
			}
		}
		if(emplList.size() > 0) {
			emplPage.setTotalSize(emplList.size());
			emplPage.setResult(emplList);
		}
		return emplPage;
	}
	
	/**
	 * 通过EsID查询对应的规则信息
	 */
	@Override
	public EsEwarningHardwareConfig getWarningRuleInfoByEsId(String esId, String userId) {
		String sourceAsString = "";
		JSONObject parseObject = null;
		TransportClient client = null;
		EsEwarningHardwareConfig config = null;
		try {
			client = esDao.getClient();
			TermQueryBuilder termQuery = QueryBuilders.termQuery("_id", esId);
			SearchResponse actionGet = client.prepareSearch("monitor-ewarning-hardware")
									.setQuery(termQuery)
									.execute()
									.actionGet();
			SearchHits hits = actionGet.getHits();
			if(hits.getHits().length > 0) {
				Long runTime;
				for (SearchHit hit : hits.getHits()) {
					sourceAsString = hit.getSourceAsString();
					parseObject = JSONObject.parseObject(sourceAsString);
					config = parseObject.getObject("config", EsEwarningHardwareConfig.class);
					config.setTopTitle(parseObject.getString("title"));
					config.setTopRemark(parseObject.getString("remark"));
					config.setTopStopTime(parseObject.getString("stopTime"));
					config.setTopSendTime(parseObject.getString("sendTime"));
					if(config.getTopStopTime() != null) {
						runTime = Long.parseLong(config.getTopStopTime()) - Long.parseLong(config.getTopSendTime());
					}else {
						runTime = (new Date().getTime())/1000 - Long.parseLong(config.getTopSendTime());
					}
					//转换分钟
					String time = converTime(((Number)runTime).intValue());
					config.setRunTime(time);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(client != null) {
				esDao.resume(client);
			}
		}
		return config;
	}
	
	public String converTime(int seconds) {
		int temp=0;
		int temp1 = 0;
		StringBuffer sb=new StringBuffer();
		temp = seconds/86400;
		temp1 = seconds/3600;
		if(temp != 0) {
			sb.append((temp<10)?""+temp+"天":""+temp+":");
		}
		if(temp1 != 0){
			temp1 = temp1/24;
			sb.append((temp1<10)?"0"+temp1+":":""+temp1+":");
		}
		
		temp=seconds%3600/60;
		sb.append((temp<10)?"0"+temp+":":""+temp+":");
		temp=seconds%3600%60;
		sb.append((temp<10)?"0"+temp:""+temp);
		return sb.toString();
	}
	
}
